Python comes with many handy methods built in. We call these built-ins.
Some of them include...
numbers = [1, 2, 3, 4, 5]
sum(numbers)
min(numbers)
max(numbers)
grid = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
for row in range(len(grid)):
for column in range(len(grid[row])):
print(grid[row][column], end='\t')
print()
NOTES
len(grid)
? (number of rows)row
? for column
?\t
mean? (tab character)row
and column
loops?grid = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
for column in range(len(grid[0])):
for row in range(len(grid)):
print(grid[row][column], end='\t')
print()
NOTES
range(len(grid[0]))
: why do we need grid[0]
?What happens when we change the order of the index operations?
grid = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
for row in range(len(grid)):
for column in range(len(grid[row])):
print(grid[column][row], end='\t') # original example was [row][column]
print()
NOTES
for
loops have the correct ranges and the grid is indexed in the correct order.Write a function that returns a list with the average of each row of the input grid.
row_average.py
¶def row_average(grid):
result = []
for row in grid:
result.append(sum(row) / len(row))
return result
grid = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
print(row_average(grid))
Write a function that computes the maximum width across all strings in a column.
column_max.py
¶def column_max_width(grid):
"""Returns the maximum width of the strings in each column. Assume the grid is regular."""
widths = []
for column in range(len(grid[0])):
max_width = None
for row in range(len(grid)):
item_width = len(grid[row][column])
if max_width is None or item_width > max_width:
max_width = item_width
widths.append(max_width)
return widths
fruits = [
['apple', 'pear', 'guava'],
['orange', 'banana', 'peach'],
['melon', 'mango', 'kiwi']
]
print(column_max_width(fruits))
NOTES
Write a function that transposes a grid.
transpose.py
¶NOTES
def transpose(grid):
"""Returns a tranposed copy of the grid."""
new_grid = []
for column in range(len(grid[0])):
new_row = []
for row in range(len(grid)):
new_row.append(grid[row][column])
new_grid.append(new_row)
return new_grid
grid = [
[1, 2],
[3, 4],
[5, 6],
[7, 8]
]
print(grid)
print(transpose(grid))
def transpose(grid):
"""Returns a tranposed copy of the grid."""
num_rows = len(grid)
num_columns = len(grid[0])
# Make new grid that is B x A
new_num_rows = num_columns
new_num_columns = num_rows
new_grid = []
for row in range(new_num_rows):
new_row = []
for column in range(new_num_columns):
new_row.append(None)
new_grid.append(new_row)
# Populate the new grid
for row in range(num_rows):
for column in range(num_columns):
new_grid[column][row] = grid[row][column]
return new_grid
grid = [
[1, 2],
[3, 4],
[5, 6],
[7, 8]
]
print(grid)
print(transpose(grid))